package com.jushu.storbox.view.mdmview;

import java.io.File;
import java.text.SimpleDateFormat;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.jushu.storbox.R;
import com.jushu.storbox.service.CloudDriveService;
import com.jushu.storbox.service.CloudDriveService.CenterShareDriveServiceServiceBinder;

public class AudioDao extends RelativeLayout implements IAudioDao, IBaseDao {
	private SeekBar seekBar;
	private ImageView btnPlayOrPause;
	private TextView musicName_tv;
	private TextView currentTime_tv;
	private TextView maxTime_tv;
	private Activity context;
	private String path;
	private RelativeLayout back;
	private int maxTime = 0;
	private int currentTime;
	private ServiceConnection conn;
	private CloudDriveService cloudDriveService;
	private Thread workThread;
	private boolean isLoop;
	private boolean isPlaying;
	private Handler handler;

	public AudioDao(Context context, String path) {
		super(context);
//		this.context = (Activity) context;
//		this.path = path;
//		this.setBackgroundColor(getResources().getColor(R.color.white));
//		initView();
//		initListener();
//		bindService();
//		test();
	}

	private void test() {
		// TODO Auto-generated method stub
		Notification mNotification=new Notification();
		NotificationManager manager=(NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
		RemoteViews notificationView  = new RemoteViews(context.getPackageName(), R.layout.notification_musicplayer);
		notificationView.setTextViewText(R.id.mdmview_notification_musicName, new File(path).getName());
		notificationView.setProgressBar(R.id.progress, 100, 0, false);
		mNotification.contentView = notificationView;
		manager.notify(1, mNotification);
	}

	private void startThread() {
		// TODO Auto-generated method stub
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				currentTime = (Integer) msg.obj;
				if (currentTime == -1) {
					isPlaying = false;
					btnPlayOrPause.setImageResource(R.mipmap.bt_widget_play_nor);
					seekBar.setProgress(0);
					currentTime_tv.setText(formatData(0));
				} else {
					seekBar.setProgress(currentTime * 100 / maxTime);
					currentTime_tv.setText(formatData(currentTime));
				}
			}
		};
		isLoop = true;
		workThread = new Thread() {
			@Override
			public void run() {
				while (isLoop) {
					while (isLoop && isPlaying) {
						Message.obtain(handler, 0, cloudDriveService.getMusicProgress()).sendToTarget();
						try {
							sleep(1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					synchronized (workThread) {
						try {
							this.wait();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} 
					}
				}
			}
		};
		workThread.start();
		Log.i("liang", "isplaying2:"+isPlaying);
	}

	private void bindService() {
		// TODO Auto-generated method stub
		Intent intent = new Intent(context, CloudDriveService.class);
		intent.setAction("musicPlayer");
		conn = new ServiceConnection() {

			@Override
			public void onServiceDisconnected(ComponentName name) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				// TODO Auto-generated method stub
				cloudDriveService = ((CenterShareDriveServiceServiceBinder) service).getService();
				initData();
				startThread();
			}
		};
		context.bindService(intent, conn, Context.BIND_AUTO_CREATE);
	}

	private void initListener() {

		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			
				context.finish();
			}
		});
		// TODO Auto-generated method stub
		seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
				// TODO Auto-generated method stub
				currentTime_tv.setText(formatData(maxTime * arg1 / 100));
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				Log.i("progress", seekBar.getProgress() + "");
				if (cloudDriveService.isMusicPlaying()) {
					cloudDriveService.setMusicProgress(maxTime * seekBar.getProgress() / 100);
				} else {
					btnPlayOrPause.setImageResource(R.mipmap.bt_widget_pause_nor);
					cloudDriveService.playMusic();
					isPlaying = true;
					cloudDriveService.setMusicProgress(maxTime * seekBar.getProgress() / 100);
					synchronized (workThread) {
						workThread.notify();
					}
				}

			}
		});
		btnPlayOrPause.setOnClickListener(playOrPauseListener);
	
	}

	private void initData() {
		// TODO Auto-generated method stub
//		maxTime = cloudDriveService.readyMusic(context,path);
//		maxTime_tv.setText(formatData(maxTime));
//		isPlaying=cloudDriveService.isMusicPlaying();
//		if(isPlaying){
//			btnPlayOrPause.setImageResource(R.drawable.bt_widget_pause_nor);
//		}
	}

	private String formatData(int time) {
		return new SimpleDateFormat("mm:ss").format(time);
	}

	private void initView() {
		View musicLayout = View.inflate(context, R.layout.mdmview_musicplayer, null);
		btnPlayOrPause = (ImageView) musicLayout.findViewById(R.id.PlayOrPause_iv);
		seekBar = (SeekBar) musicLayout.findViewById(R.id.seekBar_music);
		musicName_tv = (TextView) musicLayout.findViewById(R.id.music_name_tv);
		currentTime_tv = (TextView) musicLayout.findViewById(R.id.music_currenttime);
		back = (RelativeLayout) musicLayout.findViewById(R.id.mdmview_musicplayer_layout_back);
		maxTime_tv = (TextView) musicLayout.findViewById(R.id.music_alltime);
		musicName_tv.setText(new File(path).getName());
		btnPlayOrPause.setImageResource(R.mipmap.bt_widget_play_nor);
		this.addView(musicLayout);
	}

	OnClickListener playOrPauseListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (cloudDriveService.isMusicPlaying()) {
				btnPlayOrPause.setImageResource(R.mipmap.bt_widget_play_nor);
				cloudDriveService.pauseMusic();
				isPlaying = false;
			} else {
				btnPlayOrPause.setImageResource(R.mipmap.bt_widget_pause_nor);
				cloudDriveService.playMusic();
				isPlaying = true;
				synchronized (workThread) {
					workThread.notify();
				}
			}

		}
	};

	public static int convertPxToDip(Context context, int px) {
		float scale = context.getResources().getDisplayMetrics().density;
		return (int) (px / scale + 0.5f * (px >= 0 ? 1 : -1));
	}

	public static int convertDiptoPx(Context context, int dip) {
		float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));
	}

	@Override
	public void onDestory() {
		// TODO Auto-generated method stub
		isLoop=false;
		synchronized (workThread) {
			workThread.notify();
		}
		context.unbindService(conn);
	}

	@Override
	public void onStop() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub

	}
}
